package org.csu.mypetstore.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.AlipayConfig;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
@RequestMapping("/order")
@SessionAttributes(value = {"account", "order", "cart","userInfo"})
public class OrderController {

      @Autowired
      AccountService accountService;

      @Autowired
      OrderService orderService;

      //跳往结账界面
      @GetMapping("/checkout")
      public String GoToCheckout(Model model) {
            Account account = (Account) model.getAttribute("account");
            Cart cart = (Cart) model.getAttribute("cart");
            if (account == null) {
                  model.addAttribute("message", "请先登录");
                  return "common/Error";
            } else if (cart != null) {
                  Order order = new Order();
                  order.initOrder(account, cart);
                  model.addAttribute("order", order);
            }

            return "order/NewOrderForm";
      }

      @PostMapping("/confirmOrderForm")
      public String GoToConfirm(String shippingAddressRequired, Model model) {

            Order order = (Order) model.getAttribute("order");
            Account account = (Account) model.getAttribute("account");

            if (account == null) {
                  model.addAttribute("message", "请先登录");
                  return "common/Error";
            } else {
                  if (shippingAddressRequired == null) {
                        return "order/ConfirmOrder";
                  }
            }
            shippingAddressRequired = null;
            return "order/ShippingForm";

//            if (shippingAddressRequired == null)
//                  if (account != null)
//                        return "order/ConfirmOrder";
//                  else {
//                        shippingAddressRequired = null;
//                  }
//            return "order/ShippingForm";
      }

      //插入新订单并且查看
      @PostMapping("/newOrderAndView")
      public String NewOrderAndView(Model model) {

            Account account = (Account) model.getAttribute("account");
            Cart cart = (Cart) model.getAttribute("cart");
            Order order = (Order) model.getAttribute("order");

            if (account !=null)
                  if (order!=null) {
                        orderService.insertOrder(order);
                        model.addAttribute("cart",null);//清空购物车
                  }
            return "order/ViewOrder";
      }

      @GetMapping("/viewListOrders")
      public String viewListOrders(Model model) {

            Account account = (Account) model.getAttribute("account");



            if (account !=null) {
                  List<Order> orderList = orderService.getOrdersByUsername(account.getUsername());
                  model.addAttribute("orderList",orderList);
            }
            return "order/ListOrders";
      }

      @GetMapping(value = "/pay",produces = "text/html;charset=utf-8")
      @ResponseBody
      public String pay(String totalPrice,
                        String orderId,
                        String orderName,
                        String orderDescrip,
                        Model model) throws UnsupportedEncodingException {
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", "UTF-8", AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = new String(orderId.getBytes("ISO-8859-1"),"UTF-8");
            //付款金额，必填
            String total_amount = new String(totalPrice.getBytes("ISO-8859-1"),"UTF-8");
            //订单名称，必填
            String subject = new String(orderName.getBytes("ISO-8859-1"),"UTF-8");
            //商品描述，可空
            String body = new String(orderDescrip.getBytes("ISO-8859-1"),"UTF-8");

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //请求
            String result = null;
            try {
                  result = alipayClient.pageExecute(alipayRequest).getBody();
            } catch (AlipayApiException e) {
                  e.printStackTrace();
            }

            //输出
            return result;
      }



}
